package top.go2do.deviceSync.business.device.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.go2do.common.enumeration.CommonStatus;
import top.go2do.deviceSync.business.device.dao.DeviceRepository;
import top.go2do.deviceSync.business.device.module.DeviceHeartbeatBO;
import top.go2do.deviceSync.business.device.module.DevicePO;
import top.go2do.deviceSync.business.device.module.DeviceRegisterBO;
import top.go2do.deviceSync.configProperties.DeviceSyncModuleConfig;
import top.go2do.deviceSync.exception.DeviceSyncErrorCode;
import top.go2do.deviceSync.exception.DeviceSyncException;

import java.time.LocalDateTime;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/4/17 13:51
 */
@Slf4j
@Service
public class DeviceServiceImpl implements DeviceService{

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private DeviceSyncModuleConfig moduleConfig;

    @Override
    public void register(DeviceRegisterBO registerBO) {
        String deviceId = registerBO.getDeviceId();
        DevicePO devicePO = getById(deviceId);
        if (devicePO != null) {
            log.warn("{} existed.", deviceId);
            throw new DeviceSyncException(DeviceSyncErrorCode.DEVICE_ID_EXIST);
        } else {
            devicePO = new DevicePO();
        }
        BeanUtils.copyProperties(registerBO, devicePO);
        devicePO.setStatus(CommonStatus.NORMAL.getValue());
        devicePO.setHeartbeatInterval(moduleConfig.getHeartbeatInterval());
        deviceRepository.save(devicePO);
    }

    @Override
    public Integer heartbeat(DeviceHeartbeatBO heartbeatBO) {
        String deviceId = heartbeatBO.getDeviceId();
        DevicePO devicePO = getById(deviceId);
        if (devicePO == null) {
            log.warn("{} not exist.", deviceId);
            throw new DeviceSyncException(DeviceSyncErrorCode.DEVICE_ID_NOT_EXIST);
        }
        String appId = heartbeatBO.getAppId();
        LocalDateTime lastOnlineTime = LocalDateTime.now();
        deviceRepository.updateHeartbeatIntervalById(lastOnlineTime, appId, deviceId);
        return devicePO.getHeartbeatInterval();
    }

    private DevicePO getById(String deviceId) {
        return deviceRepository.findById(deviceId).orElse(null);
    }
}
